package com.swapper.json.io;

import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Objects;

final class JsonPath {
  private final Deque<Object> stack = new LinkedList<>();
  private static final Object NAME_PLACEHOLDER = new Object();

  public boolean isEmpty() {
    return stack.isEmpty();
  }

  public void beginArray() {
    stack.push(0);
  }

  public void endArray() {
    stack.pop();
  }

  public void beginObject() {
    stack.push(NAME_PLACEHOLDER);
  }

  public void endObject() {
    stack.pop();
  }

  public void nextIndex() {
    stack.push((Integer) stack.pop() + 1);
  }

  public void nextName(String name) {
    stack.pop();
    stack.push(Objects.requireNonNull(name));
  }

  public boolean inArray() {
    return stack.peek() instanceof Integer;
  }

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append('$');
    Iterator<Object> itr = stack.descendingIterator();
    while (itr.hasNext()) {
      Object node = itr.next();
      if (node instanceof Integer) {
        builder.append('[').append(node).append(']');
      } else {
        builder.append('.');
        if (node instanceof String) {
          builder.append(node);
        }
      }
    }
    return builder.toString();
  }
}
